import { Title } from '@/components/common/Title'
import { useState, useRef, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Slider } from '@/components/ui/slider'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { Play, Pause, Volume2, VolumeX, Upload, Maximize2, Shield, Loader2 } from 'lucide-react'
import { Card } from '@/components/ui/card'

type AspectRatio = '9:16' | '16:9'

interface AntiDetectionConfig {
  // 画面变换
  brightness: number      // 亮度调整 -20~20
  contrast: number        // 对比度调整 0.8~1.2
  saturation: number      // 饱和度调整 0.8~1.2
  hue: number            // 色调偏移 -10~10
  
  // 动态元素
  showRandomNoise: boolean // 添加随机噪点
  noiseIntensity: number  // 噪点强度 1-10
  
  // 画面调整
  cropMargin: number      // 裁剪边距 0-50px
  zoom: number           // 缩放 0.95~1.05
  rotation: number       // 旋转角度 -2~2度
  
  // 动态滤镜
  enableDynamicFilter: boolean  // 启用动态滤镜
  filterChangeInterval: number  // 滤镜变化间隔(秒)
  
  // 音频处理
  pitchShift: number     // 音调偏移 -0.1~0.1
  speedShift: number     // 速度偏移 0.98~1.02
  addBackgroundNoise: boolean  // 添加背景噪音
  audioRandomize: boolean  // 音频随机化（去重）
  
  // 文件指纹修改
  modifyMetadata: boolean  // 修改元数据（改变MD5）
  randomizeMetadata: boolean // 随机化元数据
}

interface ProcessingStatus {
  phase: 'analyzing' | 'generating' | 'completed' | 'idle'
  progress: number
  message: string
}

export default function VideoManagement() {
  const [videoFile, setVideoFile] = useState<File | null>(null)
  const [videoUrl, setVideoUrl] = useState<string>('')
  const [isPlaying, setIsPlaying] = useState(false)
  const [isLoop, setIsLoop] = useState(false)
  const [volume, setVolume] = useState([80])
  const [isMuted, setIsMuted] = useState(false)
  const [aspectRatio, setAspectRatio] = useState<AspectRatio>('16:9')
  const [floatingTitle, setFloatingTitle] = useState(() => {
    // 从 localStorage 读取上次使用的标题
    const saved = localStorage.getItem('videoManagement:floatingTitle')
    return saved || '视频悬浮播放'
  })
  
  // 防检测功能状态
  const [antiDetection, setAntiDetection] = useState(false)
  const [antiDetectionConfig, setAntiDetectionConfig] = useState<AntiDetectionConfig>({
    brightness: 5,
    contrast: 1.05,
    saturation: 1.02,
    hue: 2,
    showRandomNoise: true,
    noiseIntensity: 3,
    cropMargin: 10,
    zoom: 1.01,
    rotation: 0,  // 默认不旋转，避免问题
    enableDynamicFilter: false,
    filterChangeInterval: 30,
    pitchShift: 0,  // 默认不调整音调，避免音频问题
    speedShift: 1,  // 默认不调整速度，避免问题
    addBackgroundNoise: false,  // 默认关闭，避免复杂滤镜问题
    audioRandomize: true,  // 默认开启音频去重
    modifyMetadata: true,  // 默认开启元数据修改
    randomizeMetadata: true,  // 默认开启随机化元数据
  })

  // 防检测预设配置
  const antiDetectionPresets = {
    basic: {
      name: '基础',
      description: '轻微调整，性能最好',
      config: {
        brightness: 3,
        contrast: 1.02,
        saturation: 1.01,
        hue: 1,
        showRandomNoise: true,
        noiseIntensity: 2,
        cropMargin: 5,
        zoom: 1.005,
        rotation: 0,
        enableDynamicFilter: false,
        filterChangeInterval: 30,
        pitchShift: 0,
        speedShift: 1,
        addBackgroundNoise: false,
        audioRandomize: true,  // 音频去重
        modifyMetadata: true,  // 修改MD5
        randomizeMetadata: false,  // 基础级别不随机化
      }
    },
    standard: {
      name: '标准',
      description: '中等调整，平衡性能和效果',
      config: {
        brightness: 5,
        contrast: 1.05,
        saturation: 1.02,
        hue: 2,
        showRandomNoise: true,
        noiseIntensity: 3,
        cropMargin: 10,
        zoom: 1.01,
        rotation: 0,
        enableDynamicFilter: false,
        filterChangeInterval: 30,
        pitchShift: 0,
        speedShift: 1,
        addBackgroundNoise: false,
        audioRandomize: true,  // 音频去重
        modifyMetadata: true,  // 修改MD5
        randomizeMetadata: true,  // 随机化元数据
      }
    },
    complete: {
      name: '完全',
      description: '重度调整，最强防检测',
      config: {
        brightness: 8,
        contrast: 1.08,
        saturation: 1.05,
        hue: 5,
        showRandomNoise: true,
        noiseIntensity: 5,
        cropMargin: 20,
        zoom: 1.02,
        rotation: 0.5,
        enableDynamicFilter: true,
        filterChangeInterval: 30,
        pitchShift: 0.01,
        speedShift: 1.005,
        addBackgroundNoise: true,
        audioRandomize: true,  // 音频去重
        modifyMetadata: true,  // 修改MD5
        randomizeMetadata: true,  // 随机化元数据
      }
    }
  }

  // 应用预设配置
  const applyPreset = (presetKey: keyof typeof antiDetectionPresets) => {
    setAntiDetectionConfig(antiDetectionPresets[presetKey].config)
  }
  const [processingStatus, setProcessingStatus] = useState<ProcessingStatus>({
    phase: 'idle',
    progress: 0,
    message: ''
  })
  const [originalVideoPath, setOriginalVideoPath] = useState<string>('')
  const [processedVideoPath, setProcessedVideoPath] = useState<string>('')
  
  const videoRef = useRef<HTMLVideoElement>(null)

  // 保存悬浮窗标题到 localStorage
  useEffect(() => {
    localStorage.setItem('videoManagement:floatingTitle', floatingTitle)
  }, [floatingTitle])

  // 辅助函数：将文件路径转换为 file:// URL
  const pathToFileUrl = (filePath: string): string => {
    const normalizedPath = filePath.replace(/\\/g, '/')
    return normalizedPath.startsWith('/') 
      ? `file://${normalizedPath}` 
      : `file:///${normalizedPath}`
  }


  // 应用防检测处理
  const applyAntiDetection = async () => {
    if (!videoFile) {
      alert('请先选择视频文件')
      return
    }

    try {
      setProcessingStatus({
        phase: 'generating',
        progress: 0,
        message: '正在应用防检测处理...'
      })

      // 调用 Electron 主进程处理
      const result = await window.ipcRenderer.invoke('video:applyAntiDetection' as any, {
        videoPath: originalVideoPath,
        config: antiDetectionConfig
      }) as { success: boolean; outputPath?: string; error?: string }

      if (!result || !result.success) {
        throw new Error(result?.error || '处理失败')
      }

      // 加载处理后的视频
      const outputPath = result.outputPath || ''
      setProcessedVideoPath(outputPath)
      
      // 转换为 file:// URL 格式
      const fileUrl = pathToFileUrl(outputPath)
      console.log('处理后的视频 URL:', fileUrl)
      setVideoUrl(fileUrl)
      
      setProcessingStatus({
        phase: 'completed',
        progress: 100,
        message: '防检测处理完成！请预览效果并查看控制台日志'
      })
      
      // 在控制台输出提示
      console.log('\n✅ 防检测处理完成！')
      console.log('📊 请在Electron主进程控制台查看详细的滤镜应用情况')
      console.log('\n🎯 音频去重处理（抖音检测重点）：')
      console.log('  ✓ 随机音量调整（0.97-1.03）')
      console.log('  ✓ 5频段EQ随机化（100Hz/500Hz/1kHz/3kHz/8kHz）')
      console.log('  ✓ 轻微音调偏移（±0.5%，听感无差异）')
      console.log('  ✓ 动态范围压缩（改变音频动态特征）')
      console.log('  ✓ 立体声宽度微调')
      console.log('  → 音频指纹已完全改变，同时保持高音质')
      console.log('\n🔍 验证方法：')
      console.log('  1. 对比原视频和处理后的视频，观察画面变化（亮度、对比度、噪点等）')
      console.log('  2. 检查视频文件大小是否改变')
      console.log('  3. 使用MD5工具验证文件指纹是否不同')
      console.log('  4. 音频虽然听感一致，但波形和频谱已完全不同\n')

      // 自动播放处理后的视频
      setTimeout(() => {
        if (videoRef.current) {
          videoRef.current.play()
          setIsPlaying(true)
        }
      }, 500)

    } catch (error) {
      console.error('处理失败:', error)
      const errorMessage = error instanceof Error ? error.message : String(error)
      
      // 如果包含换行符，使用 textarea 样式的提示
      if (errorMessage.includes('\n')) {
        // 创建自定义对话框
        const confirmed = window.confirm(errorMessage)
      } else {
        alert(`处理失败: ${errorMessage}`)
      }
      
      setProcessingStatus({ phase: 'idle', progress: 0, message: '' })
    }
  }

  // 切换播放原视频或处理后的视频
  const switchToOriginalVideo = () => {
    if (originalVideoPath) {
      setVideoUrl(pathToFileUrl(originalVideoPath))
      setIsPlaying(false)
    }
  }

  const switchToProcessedVideo = () => {
    if (processedVideoPath) {
      setVideoUrl(pathToFileUrl(processedVideoPath))
      setIsPlaying(false)
    }
  }

  // 保存处理后的视频
  const saveProcessedVideo = async () => {
    if (!processedVideoPath) return

    try {
      const result = await window.ipcRenderer.invoke('video:saveProcessedVideo' as any, {
        tempPath: processedVideoPath,
        originalName: videoFile?.name
      }) as { success: boolean; savedPath?: string; error?: string }

      if (result && result.success && result.savedPath) {
        alert(`视频已保存到: ${result.savedPath}`)
      } else {
        alert('保存失败: ' + (result?.error || '未知错误'))
      }
    } catch (error) {
      console.error('保存失败:', error)
      alert('保存失败')
    }
  }

  // 监听处理进度
  useEffect(() => {
    const handleProgress = (...args: any[]) => {
      const data = args[0] as { progress: number, message: string }
      setProcessingStatus(prev => ({
        ...prev,
        progress: data.progress,
        message: data.message
      }))
    }

    const cleanup = window.ipcRenderer?.on?.('video:antiDetectionProgress' as any, handleProgress)

    return () => {
      cleanup?.()
    }
  }, [])

  // 播放/暂停切换
  const togglePlay = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause()
      } else {
        videoRef.current.play()
      }
      setIsPlaying(!isPlaying)
    }
  }

  // 音量控制
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.volume = volume[0] / 100
    }
  }, [volume])

  // 静音控制
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.muted = isMuted
    }
  }, [isMuted])

  // 循环播放控制
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.loop = isLoop
    }
  }, [isLoop])

  // 清理 Blob URL（仅对 blob: 协议有效，file:// 协议不需要）
  useEffect(() => {
    return () => {
      if (videoUrl && videoUrl.startsWith('blob:')) {
        URL.revokeObjectURL(videoUrl)
      }
    }
  }, [videoUrl])

  // 监听视频播放状态
  const handleVideoPlay = () => setIsPlaying(true)
  const handleVideoPause = () => setIsPlaying(false)

  // 获取视频容器样式
  const getVideoContainerStyle = () => {
    if (aspectRatio === '9:16') {
      return 'aspect-[9/16] max-w-sm max-h-[600px] mx-auto'
    }
    return 'aspect-video max-w-4xl mx-auto'
  }

  // 悬浮播放
  const openFloatingPlayer = async () => {
    if (!videoUrl) {
      alert('请先选择视频文件')
      return
    }

    try {
      const currentVolume = volume[0]
      const currentLoop = isLoop
      const currentMuted = isMuted
      const currentTime = videoRef.current?.currentTime || 0

      // 调试日志
      console.log('发送的标题:', floatingTitle)

      // 使用 Electron IPC 打开新窗口
      const result = await window.ipcRenderer.invoke('video:openFloatingPlayer', {
        videoUrl,
        aspectRatio,
        volume: currentVolume,
        isLoop: currentLoop,
        isMuted: currentMuted,
        currentTime,
        title: floatingTitle,
      })
      
      console.log('打开悬浮窗口结果:', result)

      if (!result.success) {
        alert(`打开悬浮窗口失败: ${result.error || '未知错误'}`)
      }
    } catch (error) {
      console.error('打开悬浮窗口失败:', error)
      alert('打开悬浮窗口失败，请检查是否在 Electron 环境中运行')
    }
  }

  return (
    <div className="container py-8 space-y-6">
      <div>
        <Title title="录播管理" description="管理您的录播内容" />
      </div>

      {/* 文件选择区域 */}
      <Card className="p-6">
        <div className="space-y-4">
          <div>
            <Label>选择视频文件</Label>
            <div className="mt-2 flex gap-2">
              <Button
                onClick={async () => {
                  try {
                    const result = await window.ipcRenderer.invoke('dialog:openFile' as any, {
                      filters: [{ name: '视频文件', extensions: ['mp4', 'avi', 'mov', 'mkv', 'flv', 'wmv', 'webm'] }],
                      properties: ['openFile']
                    }) as { canceled: boolean; filePaths: string[] }
                    
                    if (!result.canceled && result.filePaths.length > 0) {
                      const filePath = result.filePaths[0]
                      console.log('选择的文件路径:', filePath)
                      
                      // 保存真实文件路径（用于后续处理）
                      setOriginalVideoPath(filePath)
                      
                      // 转换为 file:// URL 格式
                      const fileUrl = pathToFileUrl(filePath)
                      console.log('视频 URL:', fileUrl)
                      setVideoUrl(fileUrl)
                      
                      // 设置文件信息
                      const fileName = filePath.split(/[\\/]/).pop() || 'video'
                      setVideoFile({ name: fileName } as File)
                      
                      setIsPlaying(false)
                      setProcessedVideoPath('')
                      setProcessingStatus({ phase: 'idle', progress: 0, message: '' })
                    }
                  } catch (error) {
                    console.error('选择文件失败:', error)
                    alert('选择文件失败: ' + (error instanceof Error ? error.message : String(error)))
                  }
                }}
                variant="default"
                className="flex-1 sm:flex-initial"
              >
                <Upload className="mr-2 h-4 w-4" />
                通过对话框选择
              </Button>
            </div>
            <p className="text-xs text-muted-foreground mt-2">
              💡 提示：使用"通过对话框选择"按钮可以确保防检测功能正常工作
            </p>
          </div>

          {videoFile && (
            <div className="text-sm text-muted-foreground">
              已选择: {videoFile.name}
            </div>
          )}
        </div>
      </Card>

      {/* 视频播放区域 */}
      {videoUrl && (
        <Card className="p-6 space-y-6">
          {/* 视频播放器 */}
          <div className={`bg-black rounded-lg overflow-hidden ${getVideoContainerStyle()}`}>
            <video
              ref={videoRef}
              src={videoUrl}
              className="w-full h-full"
              onPlay={handleVideoPlay}
              onPause={handleVideoPause}
              onEnded={() => !isLoop && setIsPlaying(false)}
            />
          </div>

          {/* 控制面板 */}
          <div className="space-y-6">
            {/* 播放控制 */}
            <div className="flex items-center justify-center gap-4">
              <Button
                onClick={togglePlay}
                size="lg"
                className="w-32"
              >
                {isPlaying ? (
                  <>
                    <Pause className="mr-2 h-5 w-5" />
                    暂停
                  </>
                ) : (
                  <>
                    <Play className="mr-2 h-5 w-5" />
                    播放
                  </>
                )}
              </Button>
              <Button
                onClick={openFloatingPlayer}
                size="lg"
                variant="outline"
                className="w-32"
              >
                <Maximize2 className="mr-2 h-5 w-5" />
                悬浮播放
              </Button>
            </div>

            {/* 循环播放控制 */}
            <div className="flex items-center justify-between p-4 bg-muted/50 rounded-lg">
              <Label htmlFor="loop-mode" className="cursor-pointer">
                循环播放
              </Label>
              <Switch
                id="loop-mode"
                checked={isLoop}
                onCheckedChange={setIsLoop}
              />
            </div>

            {/* 音量控制 */}
            <div className="space-y-3 p-4 bg-muted/50 rounded-lg">
              <div className="flex items-center justify-between">
                <Label>音量控制</Label>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => setIsMuted(!isMuted)}
                >
                  {isMuted || volume[0] === 0 ? (
                    <VolumeX className="h-5 w-5" />
                  ) : (
                    <Volume2 className="h-5 w-5" />
                  )}
                </Button>
              </div>
              <div className="flex items-center gap-4">
                <Slider
                  value={volume}
                  onValueChange={setVolume}
                  max={100}
                  step={1}
                  className="flex-1"
                  disabled={isMuted}
                />
                <span className="text-sm font-medium w-12 text-right">
                  {volume[0]}%
                </span>
              </div>
            </div>

            {/* 视频比例控制 */}
            <div className="space-y-3 p-4 bg-muted/50 rounded-lg">
              <Label>视频比例</Label>
              <div className="flex gap-3">
                <Button
                  variant={aspectRatio === '16:9' ? 'default' : 'outline'}
                  onClick={() => setAspectRatio('16:9')}
                  className="flex-1"
                >
                  16:9 横屏
                </Button>
                <Button
                  variant={aspectRatio === '9:16' ? 'default' : 'outline'}
                  onClick={() => setAspectRatio('9:16')}
                  className="flex-1"
                >
                  9:16 竖屏
                </Button>
              </div>
            </div>

            {/* 悬浮窗标题设置 */}
            <div className="space-y-3 p-4 bg-muted/50 rounded-lg">
              <Label htmlFor="floating-title">悬浮窗标题</Label>
              <input
                id="floating-title"
                type="text"
                value={floatingTitle}
                onChange={(e) => setFloatingTitle(e.target.value)}
                placeholder="输入悬浮窗标题"
                className="w-full px-3 py-2 bg-background border border-input rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              />
            </div>
          </div>
        </Card>
      )}

      {/* 防检测处理面板 */}
      {videoUrl && (
        <Card className="p-6 space-y-4">
          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <div className="flex items-center gap-2">
                <Shield className="h-5 w-5 text-blue-500" />
                <Label className="text-lg font-semibold">🛡️ 防检测处理</Label>
              </div>
              <p className="text-xs text-muted-foreground">
                对视频进行多重处理，让录播更像真实直播（已内置 FFmpeg，无需额外安装）
              </p>
            </div>
            <Switch
              checked={antiDetection}
              onCheckedChange={setAntiDetection}
            />
          </div>

          {antiDetection && (
            <div className="space-y-4">
              {/* 快捷预设选择 */}
              <div className="space-y-3">
                <Label className="text-sm font-semibold">⚡ 快捷预设</Label>
                <div className="grid grid-cols-3 gap-3">
                  {(Object.keys(antiDetectionPresets) as Array<keyof typeof antiDetectionPresets>).map((key) => {
                    const preset = antiDetectionPresets[key]
                    return (
                      <Button
                        key={key}
                        variant="outline"
                        size="sm"
                        onClick={() => applyPreset(key)}
                        className="flex flex-col items-center gap-1 h-auto py-3 hover:bg-primary/10 hover:border-primary transition-all"
                      >
                        <span className="font-semibold">{preset.name}</span>
                        <span className="text-xs text-muted-foreground">{preset.description}</span>
                      </Button>
                    )
                  })}
                </div>
                <p className="text-xs text-muted-foreground text-center">
                  💡 选择预设后，您仍然可以手动调整下方的各项参数
                </p>
              </div>

              {/* 画面调整 */}
              <div className="space-y-3 p-4 bg-muted/30 rounded-lg">
                <Label className="font-semibold">📺 画面调整</Label>
                
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">亮度</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.brightness}</span>
                  </div>
                  <Slider
                    value={[antiDetectionConfig.brightness]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, brightness: v}))}
                    min={-20}
                    max={20}
                    step={1}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">对比度</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.contrast.toFixed(2)}</span>
                  </div>
                  <Slider
                    value={[antiDetectionConfig.contrast * 100]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, contrast: v / 100}))}
                    min={80}
                    max={120}
                    step={1}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">饱和度</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.saturation.toFixed(2)}</span>
                  </div>
                  <Slider
                    value={[antiDetectionConfig.saturation * 100]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, saturation: v / 100}))}
                    min={80}
                    max={120}
                    step={1}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">裁剪边距</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.cropMargin}px</span>
                  </div>
                  <Slider
                    value={[antiDetectionConfig.cropMargin]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, cropMargin: v}))}
                    min={0}
                    max={50}
                    step={1}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">缩放</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.zoom.toFixed(2)}</span>
                  </div>
                  <Slider
                    value={[antiDetectionConfig.zoom * 100]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, zoom: v / 100}))}
                    min={95}
                    max={105}
                    step={1}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">旋转角度</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.rotation}°</span>
                  </div>
                  <Slider
                    value={[antiDetectionConfig.rotation * 10]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, rotation: v / 10}))}
                    min={-20}
                    max={20}
                    step={1}
                  />
                </div>
              </div>

              {/* 动态元素 */}
              <div className="space-y-3 p-4 bg-muted/30 rounded-lg">
                <Label className="font-semibold">✨ 动态元素</Label>
                
                <div className="flex items-center justify-between">
                  <Label className="text-xs">添加随机噪点</Label>
                  <Switch
                    checked={antiDetectionConfig.showRandomNoise}
                    onCheckedChange={(checked) => setAntiDetectionConfig(prev => ({...prev, showRandomNoise: checked}))}
                  />
                </div>

                {antiDetectionConfig.showRandomNoise && (
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <Label className="text-xs">噪点强度</Label>
                      <span className="text-xs text-muted-foreground">{antiDetectionConfig.noiseIntensity}</span>
                    </div>
                    <Slider
                      value={[antiDetectionConfig.noiseIntensity]}
                      onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, noiseIntensity: v}))}
                      min={1}
                      max={10}
                      step={1}
                    />
                  </div>
                )}
              </div>

              {/* 音频处理 */}
              <div className="space-y-3 p-4 bg-muted/30 rounded-lg border-2 border-orange-500/20">
                <Label className="font-semibold flex items-center gap-2">
                  🔊 音频处理
                  <span className="text-xs font-normal text-orange-500">（⭐ 平台检测重点区域）</span>
                </Label>
                <p className="text-xs text-muted-foreground">
                  音频是抖音等平台检测重复内容的主要方式，务必启用音频去重功能
                </p>
                
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">音调偏移</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.pitchShift.toFixed(3)}</span>
                  </div>
                  <Slider
                    value={[(antiDetectionConfig.pitchShift + 0.1) * 500]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, pitchShift: v / 500 - 0.1}))}
                    min={0}
                    max={100}
                    step={1}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-xs">播放速度</Label>
                    <span className="text-xs text-muted-foreground">{antiDetectionConfig.speedShift.toFixed(3)}</span>
                  </div>
                  <Slider
                    value={[(antiDetectionConfig.speedShift - 0.98) * 2500]}
                    onValueChange={([v]) => setAntiDetectionConfig(prev => ({...prev, speedShift: v / 2500 + 0.98}))}
                    min={0}
                    max={100}
                    step={1}
                  />
                </div>

                <div className="flex items-center justify-between">
                  <Label className="text-xs">添加背景噪音</Label>
                  <Switch
                    checked={antiDetectionConfig.addBackgroundNoise}
                    onCheckedChange={(checked) => setAntiDetectionConfig(prev => ({...prev, addBackgroundNoise: checked}))}
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label className="text-xs flex items-center gap-1">
                      音频去重
                      <span className="text-xs font-normal text-orange-500">（⭐ 抖音检测重点）</span>
                    </Label>
                    <p className="text-xs text-muted-foreground">
                      多重音频指纹破坏：音量、5频段EQ、音调、压缩、立体声宽度随机化
                    </p>
                    <p className="text-xs text-orange-500/80">
                      💡 强烈建议保持开启，这是对抗平台音频检测的关键
                    </p>
                  </div>
                  <Switch
                    checked={antiDetectionConfig.audioRandomize}
                    onCheckedChange={(checked) => setAntiDetectionConfig(prev => ({...prev, audioRandomize: checked}))}
                  />
                </div>
              </div>

              {/* 文件指纹修改 */}
              <div className="space-y-3 p-4 bg-muted/30 rounded-lg">
                <Label className="font-semibold">🔐 文件指纹修改</Label>
                
                <div className="flex items-center justify-between">
                  <div className="space-y-0.5">
                    <Label className="text-xs">修改文件元数据</Label>
                    <p className="text-xs text-muted-foreground">改变文件MD5值，避免被识别为同一文件</p>
                  </div>
                  <Switch
                    checked={antiDetectionConfig.modifyMetadata}
                    onCheckedChange={(checked) => setAntiDetectionConfig(prev => ({...prev, modifyMetadata: checked}))}
                  />
                </div>

                {antiDetectionConfig.modifyMetadata && (
                  <div className="flex items-center justify-between">
                    <div className="space-y-0.5">
                      <Label className="text-xs">随机化元数据</Label>
                      <p className="text-xs text-muted-foreground">每次生成不同的元数据，确保MD5不重复</p>
                    </div>
                    <Switch
                      checked={antiDetectionConfig.randomizeMetadata}
                      onCheckedChange={(checked) => setAntiDetectionConfig(prev => ({...prev, randomizeMetadata: checked}))}
                    />
                  </div>
                )}
              </div>

              {/* 应用按钮 */}
              <Button
                onClick={applyAntiDetection}
                className="w-full"
                disabled={processingStatus.phase === 'generating'}
              >
                {processingStatus.phase === 'generating' ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    处理中... {processingStatus.progress}%
                  </>
                ) : (
                  <>
                    <Shield className="mr-2 h-4 w-4" />
                    应用防检测处理
                  </>
                )}
              </Button>

              {/* 处理进度条 */}
              {processingStatus.phase === 'generating' && (
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">处理进度</span>
                    <span className="font-semibold text-primary">{processingStatus.progress}%</span>
                  </div>
                  <div className="w-full bg-secondary rounded-full h-2.5 overflow-hidden">
                    <div 
                      className="bg-primary h-2.5 rounded-full transition-all duration-300 ease-out"
                      style={{ width: `${processingStatus.progress}%` }}
                    />
                  </div>
                  <p className="text-xs text-center text-muted-foreground">
                    {processingStatus.message || '正在处理视频...'}
                  </p>
                </div>
              )}

              {/* 处理状态提示 */}
              {processingStatus.message && processingStatus.phase !== 'generating' && (
                <div className={`text-sm p-3 rounded-lg ${
                  processingStatus.phase === 'completed' 
                    ? 'bg-green-500/10 text-green-600 dark:text-green-400 border border-green-500/20' 
                    : 'bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-500/20'
                }`}>
                  {processingStatus.message}
                </div>
              )}

              {/* 视频切换和保存按钮 */}
              {processedVideoPath && (
                <div className="flex gap-2">
                  <Button
                    onClick={switchToOriginalVideo}
                    variant="outline"
                    size="sm"
                    className="flex-1"
                  >
                    播放原视频
                  </Button>
                  <Button
                    onClick={switchToProcessedVideo}
                    variant="outline"
                    size="sm"
                    className="flex-1"
                  >
                    播放处理后
                  </Button>
                  <Button
                    onClick={saveProcessedVideo}
                    variant="default"
                    size="sm"
                  >
                    保存视频
                  </Button>
                </div>
              )}
            </div>
          )}
        </Card>
      )}

      {/* 未选择视频时的提示 */}
      {!videoUrl && (
        <Card className="p-12">
          <div className="text-center text-muted-foreground space-y-2">
            <Upload className="h-12 w-12 mx-auto mb-4 opacity-50" />
            <p className="text-lg">请选择一个视频文件开始播放</p>
            <p className="text-sm">支持常见的视频格式 (MP4, WebM, OGG 等)</p>
          </div>
        </Card>
      )}
    </div>
  )
}

 